import 'dart:convert';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:yuanquan/commons/http/HttpError.dart';
import 'package:yuanquan/commons/http/HttpManager.dart';
import 'package:yuanquan/models/GetPubKeyResponse.dart';
import 'package:yuanquan/routes/Homepage.dart';
import 'package:yuanquan/routes/Main.dart';
import 'package:yuanquan/routes/WebViewPage.dart';
import 'package:yuanquan/utils/SpUtil.dart';
import 'package:yuanquan/widgets/SwitchServerDialog.dart';
import 'package:yuanquan/widgets/IconText.dart';
import 'package:fluttertoast/fluttertoast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var sealClickCount = 0;
  var _active = false;

  @override
  void initState() {
    super.initState();
    //读取持久化值
    SpUtil.getBool(SpUtil.KEY_AGREE, false).then((value){
      setState(() {
        _active = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // appBar: AppBar(
        //   title: Text("login"),
        //   backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // ),
        resizeToAvoidBottomInset: false,
        body: Stack(
          children: [
            Positioned(
              // width: 120, 
              // height: 120, 
              left: 16,
              right: 16,
              top: 80,
              child: _LoginAccountWidget(),
            ),

            Positioned(
              left: 16,
              right: 16,
              bottom: 8,
              child: _LoginBottomWidget(
                active: _active,
                onChanged: (bool value) { 
                // _active = !value;
                setState(() {
                  // value = !value;
                  _active = value;
                  SpUtil.setBool(SpUtil.KEY_AGREE, value);
                });
               },),
            ),

            Positioned(
              width: 120, 
              height: 120, 
              right: 0,
              top: 80,
              child: InkWell(onTap:() {
                if(sealClickCount++ >= 8) {
                  sealClickCount = 0;
                  showDialog(
                    context: context, 
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return SwitchServerDialog();
                    },
                  );
                }
              }, child: Image(image: AssetImage('assets/imgs/ic_seal_hand.png')),)
            ),
          ],
        ),
      );
  }

  void sealClick() {

  }

}

class _LoginAccountWidget extends StatefulWidget {
  
  
  @override
  State<StatefulWidget> createState() => _LoginAccountWidgetState();

}

/**
 * 
 */
class _LoginAccountWidgetState extends State<_LoginAccountWidget> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  var showPwd = false;

  bool _obscureText = true;

  void _toggleVisibility() {
    setState(() {
      _obscureText = !_obscureText;
    });
  }
 
  // @override
  // void dispose() {
  //   _pwdController.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      // width: 500,
      height: null,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("密码登录", style: TextStyle(fontSize: 30),),

          SizedBox(height: 70,),

          Row(
            children: [
              Text("+86"),
              SizedBox(width: 8,),
              Expanded(
                flex: 1,
                child: TextField(
                    decoration: InputDecoration(labelText:"用户名", hintText: "请输入手机号", border: InputBorder.none),
                    textInputAction: TextInputAction.next, 
                    controller: _unameController,
                  ),
                )
            ],
          ),
          Container(width: double.infinity, height: 1, color: Colors.blueGrey,),

          SizedBox(height: 20,),
          TextField(
            controller: _passwordController,
            obscureText: _obscureText,
            decoration: InputDecoration(
              labelText: '密码',
              hintText: '请输入密码',
              suffixIcon: GestureDetector(
                onTap: _toggleVisibility,
                child: Icon(
                  _obscureText ? Icons.visibility : Icons.visibility_off,
                ),
              ),
            ),
          ),
          
          Container(width: double.infinity, height: 1, color: Colors.grey,),

          SizedBox(height: 50,),
          MaterialButton(
            child: Text("登录"),
            minWidth: double.infinity,
            height: 50.0,
            color: Color.fromARGB(255, 69, 132, 222),
            textColor: Colors.white,
            onPressed: () { _gotoLogin(context); },
          ),
        ],
      ),
    );
  }

  _gotoLogin(BuildContext context) {
    if(_unameController.text.isEmpty) {
      Fluttertoast.showToast(msg: "用户名不能为空");
      return;
    }
    if(_passwordController.text.isEmpty) {
      Fluttertoast.showToast(msg: "密码不能为空");
      return;
    }
    SpUtil.getBool(SpUtil.KEY_AGREE, false).then((value){
      if (value) {
        getPubKey();
      }else {
        Fluttertoast.showToast(msg: "请阅读并同意《用户协议》和《隐私政策》");
        return;
      }
    });
    //todo
    
    // showLoadingDialog(context);
  }

  void getPubKey() async {
    HttpManager().post(
      url: '/mobile',
      options: Options(),
      // data: null,
      params: {'json' : '{"namespace":"GetPubKeyRequest","useJsonStreamer":false}'},
      // tag: "tag",
      successCallback: (data) {
        var obj = GetPubKeyResponse.fromJson(json.decode(data));
        // print("publicKey = ${obj.publicKey}");
        // _login(obj.publicKey?? "");
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context){return MainPage();}));
      },
      errorCallback: (HttpError error) {
        print(error);
      },
    );
  }

/**
 * publicKey:用于登录时加密用户名和密码(rsa加密)
 */
  void _login(String publicKey) {
    // var name = encrypt(_unameController.text, publicKey);
    // var pwd = encrypt(_passwordController.text, publicKey);
    // HttpManager().post(
    //   url: '/mobile',
    //   options: Options(),
    //   // data: null,
    //   params: {'json' : '{"deviceName":"Xiaomi M2012K11AC","deviceType":"3","networkType":"5G","osVersion":"13","password":$pwd,"phoneNo":$name,"recovery":true,"token":${Random().nextInt(0xFFFFFFFF + 1)},"username":$name,"version":"6.1.5","namespace":"LoginRequest","useJsonStreamer":false}'},
    //   // tag: "tag",
    //   successCallback: (data) {
    //     var obj = GetPubKeyResponse.fromJson(json.decode(data));
    //     print("publicKey = ${obj.publicKey}");
    //     print(data);
    //   },
    //   errorCallback: (HttpError error) {
    //     print(error);
    //   },
    // );
  }

  showLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false, //点击遮罩不关闭对话框
      builder: (context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              CircularProgressIndicator(),
              Padding(
                padding: const EdgeInsets.only(top: 26.0),
                child: Text("正在登录，请稍后..."),
              )
            ],
          ),
        );
      },
    );
  }
}

class _LoginBottomWidget extends StatelessWidget {
  const _LoginBottomWidget({Key? key, this.active = false, required this.onChanged}) : super(key: key);
  final bool active;
  final ValueChanged<bool> onChanged;


  @override
  Widget build(BuildContext context) {
    final TapGestureRecognizer _tapRecognizer1 = TapGestureRecognizer();
    final TapGestureRecognizer _tapRecognizer2 = TapGestureRecognizer();
    _tapRecognizer1.onTap = () {
      print("First span clicked!");
      // 在这里可以添加你需要的逻辑，例如导航到其他页面
    };
    _tapRecognizer2.onTap = () {
      print("Second span clicked!");
      // 在这里可以添加你需要的逻辑，例如导航到其他页面
    };

    return Container(
      // width: double.infinity,
      color: Colors.white,
      child: Column(
        // crossAxisAlignment:CrossAxisAlignment.center,
        children: [
          Text("-----------其它登录-----------"),

          SizedBox(height: 30,),

          const Wrap(
            spacing: 80,
            children: [
              IconText(imgPath: 'assets/imgs/ic_logo.png', text: "微信"),
              IconText(imgPath: 'assets/imgs/ic_logo.png', text: "游客"),
            ],
          ),

          const SizedBox(height: 70,),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Checkbox(value: active, onChanged:(value) {
                  onChanged(value ?? false);
                },
              ),
              RichText(
                text: TextSpan(
                  text: '已阅读并同意',
                  style: DefaultTextStyle.of(context).style,
                  children: <TextSpan>[
                    TextSpan(
                      text: '《用户协议》',
                      style: TextStyle(color: Colors.blue),
                      recognizer: TapGestureRecognizer()..onTap = () {Navigator.push(context, MaterialPageRoute(builder: (context){return WebviewPage(url: 'https://www.baidu.com',);}));},
                    ),
                    TextSpan(text: '和'),
                    TextSpan(
                      text: '《隐私政策》',
                      style: TextStyle(color: Colors.blue),
                      recognizer: TapGestureRecognizer()..onTap = () {Navigator.push(context, MaterialPageRoute(builder: (context){return WebviewPage(url: 'https://www.baidu.com',);}));},
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
  
}